    package com.edu.bhu.admin.controller.admin;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import com.edu.bhu.admin.domain.CosCart;
import com.edu.bhu.admin.domain.CosCosmetics;
import com.edu.bhu.admin.domain.CosOrderDetail;
import com.edu.bhu.admin.service.ICosCartService;
import com.edu.bhu.admin.service.ICosCosmeticsService;
import com.edu.bhu.admin.service.ICosOrderDetailService;
import com.edu.bhu.common.core.text.Convert;
import com.edu.bhu.common.utils.SerialUtils;
import com.edu.bhu.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.domain.CosOrder;
import com.edu.bhu.admin.service.ICosOrderService;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author wangjinao
 * @date 2022-03-17
 */
@Controller
@RequestMapping("/admin/order")
public class CosOrderController extends BaseController
{
    private String prefix = "admin/order";

    @Autowired
    private ICosOrderService cosOrderService;

    @Autowired
    private ICosOrderDetailService cosOrderDetailService;

    @Autowired
    private ICosCartService cosCartService;

    @Autowired
    private ICosCosmeticsService cosCosmeticsService;

    @RequiresPermissions("admin:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    @RequiresPermissions("admin:order:view")
    @GetMapping("/myOrder")
    public String myOrder()
    {
        return prefix + "/myOrder";
    }

    /**
     * 打开订单详情页面
     *
     * @param orderId
     * @return
     */
    @GetMapping("/orderWithDetail/{orderId}")
    public String orderWithDetail(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        //拿到订单记录
        CosOrder order = cosOrderService.selectCosOrderByOrderId(orderId);
        //拿到订单明细记录
        CosOrderDetail cosOrderDetail = new CosOrderDetail();
        cosOrderDetail.setOrderId(orderId);
        List<CosOrderDetail> details
                = cosOrderDetailService.selectCosOrderDetailList(cosOrderDetail);
        mmap.put("order", order);
        mmap.put("details", details);
        return prefix + "/orderWithDetail";
    }

    /**
     * 打开订单详情页面(admin)
     *
     * @param orderId
     * @return
     */
    @GetMapping("/orderWithDetailAdmin/{orderId}")
    public String orderWithDetailAdmin(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        //拿到订单记录
        CosOrder order = cosOrderService.selectCosOrderByOrderId(orderId);
        //拿到订单明细记录
        CosOrderDetail cosOrderDetail = new CosOrderDetail();
        cosOrderDetail.setOrderId(orderId);
        List<CosOrderDetail> details
                = cosOrderDetailService.selectCosOrderDetailList(cosOrderDetail);
        mmap.put("order", order);
        mmap.put("details", details);
        return prefix + "/orderWithDetailAdmin";
    }

    /**
     * 查询订单列表(我的)
     */
    @RequiresPermissions("admin:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CosOrder cosOrder)
    {
        startPage();
        cosOrder.setUserId(ShiroUtils.getSysUser().getUserId());
        List<CosOrder> list = cosOrderService.selectCosOrderList(cosOrder);
        return getDataTable(list);
    }

    /**
     * 查询订单列表(全部)
     */
    @RequiresPermissions("admin:order:list")
    @PostMapping("/listAll")
    @ResponseBody
    public TableDataInfo listAll(CosOrder cosOrder)
    {
        startPage();
        List<CosOrder> list = cosOrderService.selectCosOrderList(cosOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("admin:order:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CosOrder cosOrder)
    {
        List<CosOrder> list = cosOrderService.selectCosOrderList(cosOrder);
        ExcelUtil<CosOrder> util = new ExcelUtil<CosOrder>(CosOrder.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 新增订单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订单和明细（从购物车添加）
     */
    @RequiresPermissions("admin:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(String cartIds)
    {
        //生成一条订单记录
        BigDecimal total = new BigDecimal(0);
        CosOrder cosOrder = new CosOrder();
        int rows = cosOrderService.insertCosOrder(cosOrder);

        //拿到新生成的订单ID
        Long orderId = cosOrder.getOrderId();

        //根据购物车ID遍历插入明细
        String[] strings = Convert.toStrArray(cartIds);
        for (String str: strings){
            CosOrderDetail detail = new CosOrderDetail();
            detail.setOrderId(orderId);

            //拿到购物车信息
            CosCart cart = cosCartService.selectCosCartByCartId(Long.valueOf(str));
            detail.setCosId(cart.getCosId());
            detail.setNumber(cart.getNumber());
            CosCosmetics cosmetics = cart.getCosmetics();
            BigDecimal num = new BigDecimal(cart.getNumber());
            BigDecimal multiply = cosmetics.getPrice().multiply(num);
            cart.setTotal(multiply);
            detail.setPrice(cart.getTotal());
            cosOrderDetailService.insertCosOrderDetail(detail);

            //删除购物车信息
            cosCartService.deleteCosCartByCartId(Long.valueOf(str));

            //减掉商品的库存
            cosmetics.setNumber(cosmetics.getNumber()- cart.getNumber());
            cosCosmeticsService.updateCosCosmetics(cosmetics);

            //将单条总价累积到订单总价
            total = total.add(multiply);
        }

        //加上流水号和总价
        CosOrder cosOrder2 = new CosOrder();
        cosOrder2.setOrderId(orderId);
        long id = Long.parseLong(SerialUtils.generateId())+orderId;
        cosOrder2.setOrderNum(id);
        cosOrder2.setPrice(total);
        cosOrderService.updateCosOrder(cosOrder2);

        HashMap<String, Long> map = new HashMap<>();
        map.put("orderId",orderId);
        return rows > 0 ? success(map) : error();
    }

    /**
     * 新增保存订单和明细（直接购买）
     */
    @RequiresPermissions("admin:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add2")
    @ResponseBody
    public AjaxResult addSave2(CosCosmetics cosmetics)
    {
        //生成一条订单记录
        CosOrder cosOrder = new CosOrder();
        int rows = cosOrderService.insertCosOrder(cosOrder);

        //拿到新生成的订单ID
        Long orderId = cosOrder.getOrderId();

        //生成订单明细
        CosCosmetics cosmetics1 = cosCosmeticsService.selectCosCosmeticsByCosId(cosmetics.getCosId());
        CosOrderDetail detail = new CosOrderDetail();
        detail.setOrderId(orderId);
        detail.setCosId(cosmetics.getCosId());
        detail.setNumber(cosmetics.getNumber());
        BigDecimal num = new BigDecimal(cosmetics.getNumber());
        BigDecimal multiply = cosmetics1.getPrice().multiply(num);
        detail.setPrice(multiply);
        cosOrderDetailService.insertCosOrderDetail(detail);

        //减掉商品的库存
         cosmetics.setNumber(cosmetics1.getNumber()- cosmetics.getNumber());
        cosCosmeticsService.updateCosCosmetics(cosmetics);

        //加上流水号和总价
        CosOrder cosOrder2 = new CosOrder();
        cosOrder2.setOrderId(orderId);
        long id = Long.parseLong(SerialUtils.generateId())+orderId;
        cosOrder2.setOrderNum(id);
        cosOrder2.setPrice(multiply);
        cosOrderService.updateCosOrder(cosOrder2);

        HashMap<String, Long> map = new HashMap<>();
        map.put("orderId",orderId);
        return rows > 0 ? success(map) : error();
    }

    /**
     * 修改订单
     */
    @RequiresPermissions("admin:order:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        CosOrder cosOrder = cosOrderService.selectCosOrderByOrderId(orderId);
        mmap.put("cosOrder", cosOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("admin:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CosOrder cosOrder)
    {
        return toAjax(cosOrderService.updateCosOrder(cosOrder));
    }

    /**
     * 支付订单
     */
    @RequiresPermissions("admin:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/payOrder")
    @ResponseBody
    public AjaxResult payOrder(CosOrder cosOrder)
    {
        cosOrder.setPayStatus(1L);
        return toAjax(cosOrderService.updateCosOrder(cosOrder));
    }

    /**
     * 关闭订单
     */
    @RequiresPermissions("admin:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/closeOrder")
    @ResponseBody
    public AjaxResult closeOrder(CosOrder cosOrder)
    {
        cosOrder.setStatus(2L);
        //退还库存
        CosOrderDetail cosOrderDetail = new CosOrderDetail();
        cosOrderDetail.setOrderId(cosOrder.getOrderId());
        List<CosOrderDetail> cosOrderDetails
                = cosOrderDetailService.selectCosOrderDetailList(cosOrderDetail);
        for(CosOrderDetail d :cosOrderDetails){
            d.getNumber();
            CosCosmetics cosmetics = new CosCosmetics();
            CosCosmetics c
                    = cosCosmeticsService.selectCosCosmeticsByCosId(d.getCosId());
            cosmetics.setCosId(d.getCosId());
            cosmetics.setNumber(c.getNumber()+d.getNumber());
            cosCosmeticsService.updateCosCosmetics(cosmetics);
        }
        return toAjax(cosOrderService.updateCosOrder(cosOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("admin:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(cosOrderService.deleteCosOrderByOrderIds(ids));
    }
}
